package com.cqndt.disaster.device.common.util;

import java.util.List;
import java.math.BigDecimal;
import java.util.ArrayList;
import com.cqndt.disaster.device.common.enums.ConstantErrorEnum;
import com.cqndt.disaster.device.common.exception.ContrlException;
import static com.cqndt.disaster.device.common.util.CRC8.FindCRC;

/**
 * @author lhl
 * @Description 数字进制转换工具类
 * @Date 2019/1/5 14:02
 */
public class NumberChangeUtil {

    /**
     * 10进制整数转16进制浮点数
     *
     * @param num
     * @return
     */
    public static String decimalToFloat(BigDecimal num) {
        if(num.compareTo(BigDecimal.ZERO)==0){
            return "00000000";
        }
        return sortHighShort(Integer.toHexString(Float.floatToIntBits(num.floatValue())));
    }

    /**
     * @param str
     * @return 高低调整顺序
     **/ 
    public static String sortHighShort(String str) {
        String[] src = new String[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            src[i] = str.substring(2 * i, 2 * i + 2);
        }
        StringBuffer ok = new StringBuffer();
        for (int i = src.length - 1; i >= 0; i--) {
            ok.append(src[i]);
        }
        return ok.toString();
    }

    /**
     * @param str
     * @return 字符串转byte[]
     **/
    public static byte[] stringToByte(String str) {
        List<String> list = new ArrayList<>();
        String[] split = str.split("");
        byte[] bytes = new byte[split.length / 2];
        for (int i = 0; i < split.length; i += 2) {
            list.add(split[i] + split[i + 1]);
        }
        for (int j = 0; j < list.size(); j++) {
                bytes[j] = (byte) Integer.parseInt(list.get(j), 16);
        }
        return bytes;
    }

    public static void main(String[] args) {
        /*String s="00002040";
        s=sortHighShort(s);
        Float value = Float.intBitsToFloat(Integer.valueOf(s.trim(), 16));
        System.out.println(value);
*/
/*        float f1 = 2.5f;
        BigDecimal f=new BigDecimal(2.0);
        System.out.println(Float.floatToIntBits(f1));
        System.out.println();*/

//        System.out.println(sortHighShort(padLeft(Integer.toHexString("F60D0E005c260560ea00000a000000cc".length() / 2), 4)));

/*        System.out.println(decimalToFloat(new BigDecimal(10)));
        System.out.println(setAlarm(10));*/
        System.out.println(  padLeft(Integer.toHexString(FindCRC(stringToByte("0faf020202".toString()))), 2));
        System.out.println(sortHighShort(padLeft(Integer.toHexString(15),4)));

    }


    /**
     * @param upLoad 值
     * @return 上传间隔数据
     **/
    public static String upLoadCycle(BigDecimal upLoad) {
        //gps 上报周期(4b)+静止上报周期(4b)
        //86400000->05265c00  60000->0000ea60
        String str = sortHighShort("05265c00");

        //10 ->16 进制-静止上报周期
        String hexString =Integer.toHexString(upLoad.multiply(new BigDecimal(1000)).multiply(new BigDecimal(60)).intValue());
        if (hexString.length()>8){
            throw new ContrlException(ConstantErrorEnum.PARAM_MAX_UPLOAD);
        }
        //保留8位
        String hex = sortHighShort(padLeft(hexString,8));

        return str + hex;
    }

    /**
     * @param str 保留位数的串
     * @param len 保留的位数
     * @return 保留指定位数
     **/
    public static String padLeft(String str, int len) {
        String pad = "0000000000000000";

        return len > str.length() && len <= 16 && len >= 0 ? pad.substring(0, len - str.length()) + str : str;
    }

    /**
     * @param vibration 值
     * @return 10-》16进制2字节整数
     **/
    public static String setVibration(Integer vibration) {
        String hexString = Integer.toHexString(vibration);
        if (hexString.length() > 4){
            throw new ContrlException(ConstantErrorEnum.PARAM_MAX_VIBRATION);
        }
        //保留4位
        return padLeft(hexString,4);
    }

//    /**
//     * 报警时间
//     * @param warnTime 时间  s
//     * @return
//     */
//    public static String setWarnTime(Integer warnTime) {
//        String onOff = "01";
//        String hexString = Integer.toHexString(warnTime*1000);
//        if (hexString.length() > 8){
//            throw new ContrlException(ConstantErrorEnum.PARAM_MAX_WARNTIME);
//        }
//        return  onOff + sortHighShort(padLeft(hexString, 8));
//    }

    /**
     * 声光报警参数转换
     * @param soundLight 0-7
     * @return
     */
    public static String setAlarms(Integer soundLight) {
        String onOff = "0200";
        String hexString = Integer.toHexString(soundLight);
        if (hexString.length() > 2){
            throw new ContrlException(ConstantErrorEnum.PARAM_MAX_WARNTIME);
        }
        return  onOff + padLeft(hexString, 2);
    }

    /**
     * 采样间隔
     * @param sampling 值
     * @return
     */
    public static String setSamp(Integer sampling){
        String s = "00"+sortHighShort(padLeft(Integer.toHexString(sampling),4));
        return s;
    }

    /**
     * @description 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[],Integer size) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 设备升级 data
     * @param indexes 分包索引
     * @param len 长度
     * @param data 数据
     * @return
     */
    public static String up(Integer indexes,Integer len,String data){
        StringBuilder builder = new StringBuilder();
        builder.append(sortHighShort(padLeft(Integer.toHexString(indexes),8)));
        builder.append(sortHighShort(padLeft(Integer.toHexString(len),8)));
        builder.append(sortHighShort(padLeft(Long.toHexString(CRC8.crc32(NumberChangeUtil.stringToByte(data))),8)));
        builder.append(data);
        return builder.toString();
    }

    /**
     * 服务器向设备发送最新软件版本
     * @param version 最新软件版本
     * @param len 升级包总长度
     * @param pakeageNum 分包总个数
     * @param data 文件总的内容
     * @return
     */
    public static String sendNewVersionData(String version,Integer len,Integer pakeageNum,String data){
        StringBuilder builder = new StringBuilder();
        builder.append(sortHighShort(version.replaceAll("\\.", "")));//最新软件版本（2B）
        builder.append(sortHighShort(padLeft(Integer.toHexString(len),8)));//升级包总长度。（4B）
        builder.append(sortHighShort(padLeft(Long.toHexString(CRC8.crc32(NumberChangeUtil.stringToByte(data))),8)));//crc校验（4B）
        builder.append(sortHighShort(padLeft(Integer.toHexString(pakeageNum), 8)));//分包总个数（4B）
        return builder.toString();
    }
}
